import { ChangeDetectionStrategy, Component, Inject, Input, OnChanges, OnInit, Optional, SimpleChanges, ViewChild } from '@angular/core';
import { basicsList, defaultFields, layoutList } from '../../utils/formItemConfig';
import { cloneDeep } from 'lodash-es';
import { castArray } from "lodash-es";
import { MonkFormDesign, MonkFormDesignConfig, MONK_FORMDEISGN_CONFIG } from "./monk-form-design.interface";
import { DesignFormItemPropertiesComponent } from './components/design-form-item-properties/design-form-item-properties.component';
import { PreviewFormDesignService } from './preview-form-design/preview-form-design.service';
declare const JSONPath: any;
@Component({
  // eslint-disable-next-line
  selector: 'monk-form-design',
  templateUrl: './monk-form-design.component.html',
  styleUrls: ['./monk-form-design.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class MonkFormDesignComponent implements OnInit, OnChanges {
  @Input() fields: Array<string> = defaultFields
  @Input() attrLists: Array<any> = []

  //@ViewChild('appDesignFormItemProperties') public appDesignFormItemProperties: DesignFormItemPropertiesComponent;
  //@Input() initData: any
  basicArray: Array<MonkFormDesign.AllComponentType> = basicsList.filter(item => this.fields.includes(item.type));
  layoutArray:  Array<MonkFormDesign.AllLayout> = layoutList.filter(item => this.fields.includes(item.type));

  data: MonkFormDesign.Config = {
    list: [],
    config: {
      "layout": "horizontal",
      "labelCol": {
        "xs": 4,
        "sm": 4,
        "md": 4,
        "lg": 4,
        "xl": 4,
        "xxl": 4
      },
      "labelWidth": 100,
      "labelLayout": "flex",
      "wrapperCol": {
        "xs": 18,
        "sm": 18,
        "md": 18,
        "lg": 18,
        "xl": 18,
        "xxl": 18
      },
      "hideRequiredMark": false,
      "customStyle": "",
      "previewWidth": 800
    }
  }
  selectItem: any = {
    key: ""
  }
  startType: string
  activeKey: number
  noModel: Array<string> = [
    "button",
    "divider",
    "card",
    "grid",
    "tabs",
    "table",
    "alert",
    "text",
    "html"
  ]

  constructor(
    @Optional() @Inject(MONK_FORMDEISGN_CONFIG) public config: MonkFormDesignConfig,
    private _previewFormDesignService: PreviewFormDesignService,
  ) {
    if (config?.overrideConfig) {
      config.overrideConfig.forEach(config => {
        const findIndex = basicsList.findIndex(b => b.type == config.type)
        if (findIndex != -1) {
          basicsList[findIndex] = config
        }
        
      })
    }
  }

  ngOnInit(): void {
    console.log()
    //this.data = cloneDeep(this.initData)
  }

  ngOnChanges(changes: SimpleChanges): void {
    if (changes.fields) {
      this.basicArray = basicsList.filter(item => this.fields.includes(item.type))
      this.layoutArray = layoutList.filter(item => this.fields.includes(item.type));
    }
    // if (changes.data) {
    //   this.data = changes.data.currentValue
    // }
    if (changes.attrLists) {
      //console.log(changes.attrLists)
    }
  }

  public init(data) {
    this.data = cloneDeep(data)
  }
  getInitInfo(showTemplate, jsonMetadata) {
    console.log(jsonMetadata);
    
    const showTemplateXml = JSON.parse(showTemplate)
    const result = this._previewFormDesignService.getFlatList({list: showTemplateXml.list})
    const final = {}
    for (const item of result) {
      const path = item.key.replace('.content', '')
      const result = JSONPath.JSONPath({ path: path, json: jsonMetadata, resultType: 'all' })
      if (result[0]?.value?.content) {
        final[item.key] = result[0]?.value?.content
      }
    }
    const find = result.find(item => item.type == 'process')
    if (find) {
      const node = this.getProcessNode((jsonMetadata as any)?.record)
      if (node) {
        final[find.key] = node
      }
    }
    const width = showTemplateXml.config.previewWidth;

    return {
      initValue: final,
      showTemplateXml,
      width
    }
  }
  getProcessNode(json) {
    const formatShowJson = (jsonData) => {
      if (jsonData.node) {
        return castArray(jsonData.node);
      }
      if (jsonData.block) {
        const blocks = castArray(jsonData.block)
        for (let i = 0; i < blocks.length; i++) {
          const result = formatShowJson(blocks[i])
          if (result) {
            return result;
          }
        }
      }
      return null;
    }
    return formatShowJson(json)
  }
  public recursiveGetComponentList() {
    const list = []
    const recursivePush = (item: MonkFormDesign.AllType) => {
      //if (['input','textarea','number','select','checkbox','radio','date','rate','slider'])
      if ('batch' == item.type ||  'card' == item.type ||  'block' == item.type) {
        item.list.forEach(recursivePush)
      } else if (item.type == 'tabs' || item.type == 'grid' || item.type == 'collapse') {
        item.columns.forEach(col => {
          col.list.forEach(recursivePush)
        })
      } else {
        list.push(item)
      }
    }
    this.data.list.forEach(recursivePush)
    return list
  }

  getData() {
    return cloneDeep(this.data)
  }

  generateKey(list, index) {
    // 生成key值
    const key = list[index].type + "_" + new Date().getTime();
    // this.$set(list, index, {
    //   ...list[index],
    //   key,
    //   model: key
    // });
    list[index].key = list[index].model = key
    // list[index] = {
    //   ...list[index],
    //   key,
    //   model: key
    // }
    if (this.noModel.includes(list[index].type)) {
      // 删除不需要的model属性
      delete list[index].model;
    }
  }

  handleSetSelectItem(record) {
          // 设置selectItem的值
    this.selectItem = record;

    // 判断是否选中控件，如果选中则弹出属性面板，否则关闭属性面板
    if (record.key) {
      this.startType = record.type;
      this.changeTab(2);
    } else {
      this.changeTab(1);
    }
  }

  handleStart(type) {
    this.startType = type;
  }

  changeTab(e) {
    this.activeKey = e;
  }
}
